package com.ubireality.repository;

import javax.inject.Inject;
import javax.persistence.EntityManager;

import com.mysema.query.jpa.HQLTemplates;
import com.mysema.query.jpa.impl.JPADeleteClause;
import com.mysema.query.jpa.impl.JPAQuery;
import com.mysema.query.types.EntityPath;
import com.ubireality.module.basic.Identifiable;

public abstract class AbstractRepository<T extends Identifiable> implements
		Repository<T, Long> {

	@Inject
	private EntityManager entityManager;

	protected JPAQuery query() {
		return new JPAQuery(entityManager, HQLTemplates.DEFAULT);
	}

	protected JPAQuery from(EntityPath<?> entity) {
		return query().from(entity);
	}

	protected JPADeleteClause delete(EntityPath<?> entity) {
		return new JPADeleteClause(entityManager, entity, HQLTemplates.DEFAULT);
	}

	protected void detach(Object entity) {
		entityManager.detach(entity);
	}

	protected <E> E find(Class<E> type, Long id) {
		return entityManager.find(type, id);
	}

	protected void persist(Object entity) {
		entityManager.persist(entity);
	}

	protected <E> E merge(E entity) {
		return entityManager.merge(entity);
	}

	protected <E extends Identifiable> E persistOrMerge(E entity) {
		if (entity.getId() != null) {
			return merge(entity);
		}
		persist(entity);
		return entity;
	}

	protected void remove(Object entity) {
		entityManager.remove(entity);
	}

}
